using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.AspNetCore.Authorization;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/files")]
public class FileController : ControllerBase
{
    private readonly string _root = "uploads";
    private readonly ILogger<FileController> _logger;

    public FileController(ILogger<FileController> logger)
    {
        _logger = logger;
    }

    [AllowAnonymous]          // 如需鉴权改成 [Authorize]
    [HttpGet("{dateFolder}/{fileName}")]
    public async Task<IActionResult> GetFile(string dateFolder, string fileName)
    {
        try
        {
            var path = Path.Combine(_root, dateFolder, fileName);
            if (!System.IO.File.Exists(path))
            {
                _logger.LogWarning("文件不存在: {Path}", path);
                return NotFound(new { error = "文件不存在" });
            }

            var provider = new FileExtensionContentTypeProvider();
            if (!provider.TryGetContentType(fileName, out var mime))
            {
                // 自定义MIME类型映射
                mime = GetCustomMimeType(fileName);
            }

            _logger.LogInformation("文件访问: {Path}, MIME: {Mime}", path, mime);

            // 使用异步文件读取
            var fullPath = Path.GetFullPath(path);
            return await Task.FromResult(PhysicalFile(fullPath, mime, enableRangeProcessing: true));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件访问失败: {DateFolder}/{FileName}", dateFolder, fileName);
            return StatusCode(500, new { error = "文件访问失败" });
        }
    }

    /// <summary>
    /// 获取自定义MIME类型
    /// </summary>
    private string GetCustomMimeType(string fileName)
    {
        var extension = Path.GetExtension(fileName).ToLowerInvariant();
        return extension switch
        {
            ".txt" => "text/plain; charset=utf-8",
            ".md" => "text/markdown; charset=utf-8",
            ".json" => "application/json; charset=utf-8",
            ".xml" => "application/xml; charset=utf-8",
            ".csv" => "text/csv; charset=utf-8",
            ".log" => "text/plain; charset=utf-8",
            ".ini" => "text/plain; charset=utf-8",
            ".conf" => "text/plain; charset=utf-8",
            ".config" => "text/plain; charset=utf-8",
            ".js" => "application/javascript; charset=utf-8",
            ".css" => "text/css; charset=utf-8",
            ".html" => "text/html; charset=utf-8",
            ".htm" => "text/html; charset=utf-8",
            ".php" => "text/plain; charset=utf-8",
            ".py" => "text/plain; charset=utf-8",
            ".java" => "text/plain; charset=utf-8",
            ".c" => "text/plain; charset=utf-8",
            ".cpp" => "text/plain; charset=utf-8",
            ".cs" => "text/plain; charset=utf-8",
            ".sql" => "text/plain; charset=utf-8",
            ".sh" => "text/plain; charset=utf-8",
            ".bat" => "text/plain; charset=utf-8",
            ".ps1" => "text/plain; charset=utf-8",
            ".jpg" => "image/jpeg",
            ".jpeg" => "image/jpeg",
            ".png" => "image/png",
            ".gif" => "image/gif",
            ".bmp" => "image/bmp",
            ".webp" => "image/webp",
            ".svg" => "image/svg+xml",
            ".ico" => "image/x-icon",
            ".tiff" => "image/tiff",
            ".tif" => "image/tiff",
            ".pdf" => "application/pdf",
            ".doc" => "application/msword",
            ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            ".ppt" => "application/vnd.ms-powerpoint",
            ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            ".xls" => "application/vnd.ms-excel",
            ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            ".rtf" => "application/rtf",
            ".odt" => "application/vnd.oasis.opendocument.text",
            ".ods" => "application/vnd.oasis.opendocument.spreadsheet",
            ".odp" => "application/vnd.oasis.opendocument.presentation",
            ".zip" => "application/zip",
            ".rar" => "application/vnd.rar",
            ".7z" => "application/x-7z-compressed",
            ".tar" => "application/x-tar",
            ".gz" => "application/gzip",
            ".mp3" => "audio/mpeg",
            ".wav" => "audio/wav",
            ".ogg" => "audio/ogg",
            ".flac" => "audio/flac",
            ".aac" => "audio/aac",
            ".mp4" => "video/mp4",
            ".avi" => "video/x-msvideo",
            ".mov" => "video/quicktime",
            ".wmv" => "video/x-ms-wmv",
            ".flv" => "video/x-flv",
            ".webm" => "video/webm",
            ".mkv" => "video/x-matroska",
            ".ttf" => "font/ttf",
            ".otf" => "font/otf",
            ".woff" => "font/woff",
            ".woff2" => "font/woff2",
            ".eot" => "application/vnd.ms-fontobject",
            _ => "application/octet-stream"
        };
    }
}